<?php
/*!*****************************************************************************************************
 *
 *	@file		class.mysql.php
 *	@author		Jos Pape
 *	@version	1.0
 *	@brief		Contains a class that runs queries using a different read and write server
 *
 ******************************************************************************************************/

/*!**************************************************************************
 *	@class 		MySQL
 *	@author		Jos Pape
 *	@version	1.0
 *	@brief 		Facilitates running a query
 **************************************************/ 

class MySQL
{
	/*!******************************
	 * @brief	holds the read connection ID
	 */
	var $readConnection;
	
	/*!******************************
	 * @brief	holds the write connection ID
	 */
	var $writeConnection;
	
	/*!******************************
	 * @brief	holds the mail connection ID
	 */
	var $mailConnection;
	
	/*!******************************
	 * @brief	holds the DWG connection ID
	 */
	var $DWGConnection;
	
	/*!******************************
	 * @brief	holds the read server location
	 */
	var $readlocation = "localhost";
	
	/*!******************************
	 * @brief	holds the read server username
	 */
	var $readusername = "pR31SgeZ0cht";
	
	/*!******************************
	 * @brief	holds the read server password
	 */
	var $readpassword = "ls#.jf9$43j.oit%0wbg";
	
	/*!******************************
	 * @brief	holds the read server database name
	 */
	var $readdatabase = "prijsgezocht_nl";
	
	/*!******************************
	 * @brief	holds the write server location
	 */
	var $writelocation = "localhost";
	
	/*!******************************
	 * @brief	holds the write server username
	 */
	var $writeusername = "pR31SgeZ0cht";
	
	/*!******************************
	 * @brief	holds the write server password
	 */
	var $writepassword = "ls#.jf9$43j.oit%0wbg";
	
	/*!******************************
	 * @brief	holds the write server database name
	 */
	var $writedatabase = "prijsgezocht_nl";
	
	/*!******************************
	 * @brief	holds additional log entry
	 */
	var $addToLog = "";		
	
	/*!******************************
	 * @brief	determins if we alwaysuse the write from now on
	 */
	var $useWrite = false;
			
			
			
	/*!************
	 * @brief	The constructor.
	 * @retval	Boolean	True.
	 */ 
	function MySQL() 
	{
		
		$this->makeConnection();
		// we return true, all the connections are made			
		return True;
	}	
	
	function makeConnection()
	{
	/*************
		 * first we make the read connection
		 */
		if (!$this->readConnection = mysql_connect($this->readlocation, $this->readusername, $this->readpassword))
		{
			// connection failed so we return false
			//echo "ERROR - kon de read connexie niet maken";
			mail("jos@seniorgroep.nl", "Error In Query","Could not connect to the READ database.");
			//exit;
			return false;			
		}
		else
		{
			if (!mysql_select_db($this->readdatabase, $this->readConnection))
			{
			  //  echo "ERROR - kon de database niet selecteren";
//			    exit;
				mail("jos@seniorgroep.nl", "Error In Query","Could not Select the READ database.".mysql_error());
				return false;
			}
			// this should be set hard-core instead of runtime
			// if you are reading this, it means this hasn't been done yet, so FIX IT!
			$query = "SET default_week_format=3";
			mysql_query($query, $this->readConnection);
		}	
		
		/*************
		 * second we make the write connection
		 */
		if (!$this->writeConnection = mysql_connect($this->writelocation, $this->writeusername, $this->writepassword))
		{
			// connection failed so we return false
	//		echo "Error - Kon geen connexie maken m,et de Write DB";
			//exit;
			mail("jos@seniorgroep.nl", "Error In Query","Could not connect to the WRITE database.");
			return false;			
		}
		else
		{
			if (!mysql_select_db($this->writedatabase, $this->writeConnection))
			{
			  //  echo "ERROR - kon de write database niet selecteren";
//			    exit;
				mail("jos@seniorgroep.nl", "Error In Query","Could not select the WRITE database.");
				return false;
			}
			// this should be set hard-core instead of runtime
			// if you are reading this, it means this hasn't been done yet, so FIX IT!
			$query = "SET default_week_format=3";
			mysql_query($query, $this->writeConnection);
		}
	}
	
	function useDatabase($database)
	{
		$this->readdatabase = $database;
		$this->writedatabase = $database;
		$this->makeConnection();
	}

	/*!************
	 * @brief	Closes all made connexxion
	 * @retval	boolean true
	 */
	function closeConnexions()
	{
		mysql_close($this->readConnection);
		mysql_close($this->writeConnection);
		return true;
	}
	
	
	/*!************
	 * @brief	Gets the microseconds in UNIXtime
	 * @retval	float time in seconds with comma added micro seconds
	 */
	function getMicroTime() 
	{
	    list($usec, $sec) = explode(" ",microtime());
	    return ((float)$usec + (float)$sec);
	} 
	
	/*!**********
	 * @brief return the last INSERT ID
	 * @retval number
	 */
	function lastInsertID()
	{
		return mysql_insert_id($this->writeConnection);
	}

	/*!************
	 * @brief	running a query, it automaticly selects the correct read or write connection
	 * @retval	Array of results OR false(if array returned a error).
	 */ 
	function runQuery($query, $useWrite = false)
	{
		$STARTTIJD = $this->getMicroTime();
		// remove newlines
		$query = str_replace("\n"," ",$query);
		// remove spaces around the query
		$query = trim($query);
		
		if (!empty($query))
		{
			$useConnection = false;
			if($useWrite)
			{	
				/* force write connection, this doesn't infulence the always use write */
				$useConnection = $this->writeConnection;	
			}
			elseif($this->useWrite)
			{
				/* there has been a update so we use the writwe connection */
				$useConnection = $this->writeConnection;				
			}
			elseif (
				   strtoupper(substr($query, 0, 7)) == "REPLACE"
				|| strtoupper(substr($query, 0, 6)) == "UPDATE" 
				|| strtoupper(substr($query, 0, 6)) == "DELETE" 
				|| strtoupper(substr($query, 0, 6)) == "INSERT" 
				|| strtoupper(substr($query, 0, 6)) == "CREATE"
				|| strtoupper(substr($query, 0, 6)) == "UNLOCK" 
				|| strtoupper(substr($query, 0, 5)) == "ALTER"
				|| strtoupper(substr($query, 0, 4)) == "DROP"
				|| strtoupper(substr($query, 0, 4)) == "LOCK"
				|| strtoupper(substr($query, 0, 4)) == "SHOW"
				|| strtoupper(substr($query, 0, 5)) == "START"
				|| strtoupper(substr($query, 0, 3)) == "SET"
				|| strtoupper(substr($query, 0, 6)) == "COMMIT"
				|| strtoupper(substr($query, 0, 8)) == "ROLLBACK"
			)
			{	/* write connection */
				$useConnection = $this->writeConnection;
				/* always use write connection from now on, since we need to show the new data */
				$this->useWrite = true;	
			}
			elseif (strtoupper(substr($query, 0, 6)) == "SELECT")
			{	/*read connection*/
				$useConnection = $this->readConnection;
			}
			else
			{
				$this->reportError('Coulnd select the connextion in the class', $query, '0');
				return false;
			}
			
			/****************
			 * Run the query 
			 ***************/			
			if (
					$useConnection 
				)
			{
				if ($result = mysql_query($query, $useConnection))
				{
					// insert into logfile
					//$this->logToFile($query, ($this->getMicroTime() - $STARTTIJD));
					
					// check time for this query
					if (($this->getMicroTime() - $STARTTIJD) > 20) /* 20 sec. is te lang */
					{
						$this->reportError("Query duurt te lang: (".($this->getMicroTime() - $STARTTIJD)." sec)\nquery:\n".$query."\n", $query, mysql_errno($useConnection));
					}					
					return $result;
				}
				else
				{
					$this->reportError(mysql_error($useConnection), $query, mysql_errno($useConnection));
					return false;
				}
			}
			else
			{
				//$this->reportError('Coulnd select the connextion in the class', $query, '0');
				return false;
			}
		}
		else
		{
			$this->reportError("empty query:\n".$query."\n", __line__, __file__);
			return false;
		}
	}
	
	/*!************
	 * @brief	function to see if a table estist
	 * @retval	Boolean true is is exists
	 */
	function tableExists($tableName) 
	{
		if (@mysql_query("SELECT 1 FROM ".$tableName." LIMIT 0", $this->readConnection)) 
		{
			return true;
		}
		else 
		{
			return false;
		}
	}

	/*!************
	 * @brief	reportError
	 * @retval	send a mail to the administrator with the error
	 */ 	
	function reportError($error, $query, $errorNo)
	{
		// $this->writeLogFile();
		if (isset($_GET) && !empty($_GET))
		{
			$getvalues = "";
			foreach ($_GET AS $key => $value)
			{
				$getvalues .= $key." = ".$value."<br>";
			}
		}
		if (isset($_POST) && !empty($_POST))
		{
			$postvalues = "";
			$temp = "";
			if(is_array($_POST))
			{
				foreach ($_POST AS $key => $value)
				{
					if (is_array($value))
					{
						$temp .= "Array :<b>";
						foreach ($value AS $k => $v)
						{
							$temp .= "&nbsp;&nbsp;&nbsp;".$k." = ".$v."<br>";
						}
						$value = $temp;
					}
					$postvalues .= $key." = ".$value."<br>";
				}
			}
		}
		$getvalues  = !isset($getvalues)  ? "geen waardes in de url<br>"  : "waardes in de  url:<br>".$getvalues;
		$postvalues = !isset($postvalues) ? "geen waardes in de post<br>" : "waardes in de post:<br>".$postvalues;
		$computer   = "computer ips:<br>".(isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:"onbekend")."<br>".(isset($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:"");
			
		mail("jospape@hotmail.com", "Prijsgezocht QueryErrors", "
							ErrorNo: '".$errorNo."',
							Query: '".$query."',
							Error: '".$error."',
							URL: 'pagina: ".$_SERVER['PHP_SELF']."<br>van pagina: ".(isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:"")."',
							Datum: ".date("d-m-Y H:i")."
							UserID: ".(isset($_SESSION['login']['id'])?$_SESSION['login']['id']:"NULL").",
							GetPost: '".$getvalues."\n".$postvalues."'");
	}
	
	function sendIntMail($user_id, $subject, $body)
	{
		mail(
				"jospape@hotmail.com",
				$subject,
				$body,
				"From: Prijsgezocht <noreply@prijsgezocht.nl>\nReply-To: "
			);
	}
}


?>
